package com.huanletao.water;


import lombok.SneakyThrows;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 图片添加水印工具类
 * @Author: macro
 * @Date: 2022/8/9
 * @Version: V1.0
 */
public class WatermarkUtils {

    private static Logger logger = LoggerFactory.getLogger(WatermarkUtils.class);
    /*水印字字体大小*/
    private final static Integer FONT_SIZE = 36;
    /*水印字字体*/
    private final static String FONT_NAME = "宋体";
    /*水印字体透明度*/
    private final static Float ALPHA = 0.9f;

    /**

     * @param textMap    添加水印的Map, key:value 形式。
     * @Author huangjf
     * @Description 加水印
     * @Date 2023/05/05 11:12
     **/
    @Deprecated
//    public static void waterMark(File sourceFile, File destFile, LinkedHashMap<String, String> textMap) throws Exception {
//        try {
//            /*组装水印文字*/
//            List<String> textList = getTextList(textMap);
//            logger.info("输出的目标文件:{},原文件 ：{}", destFile, sourceFile);
//            Img img = Img.from(ImageIO.read(sourceFile)).setPositionBaseCentre(false);
//            int index = 1;
//            Image imageFile = ImageIO.read(sourceFile);
//            for (String pressText : textList) {
//                int y = index * 40;
//                imageFile = img.pressText(pressText, Color.white, new Font(FONT_NAME, Font.BOLD, FONT_SIZE), 0, y, ALPHA).getImg();
//                index++;
//            }
//            ImgUtil.write(imageFile, destFile);
//            logger.info("输出的目标文件:{},原文件 ：{}", destFile, sourceFile);
//        } catch (IOException e) {
//            logger.error(e.getMessage(), e);
//            throw new RuntimeException("添加水印失:" + e.getMessage());
//        }
//    }

    /**
     * @param textMap
     * @return
     */
    private static List<String> getTextList(LinkedHashMap<String, String> textMap) {
        return null;
    }

    /**
     * 构建文本lisi，
     *
     * @param textMap
     * @return
     */
    private static List<String> buildTextList(LinkedHashMap<String, String[]> textMap) {
        String[] textArray = new String[3];
        for (Map.Entry<String, String[]> entry : textMap.entrySet()) {
            String key = entry.getKey();
            String[] value = entry.getValue();
            String row = value[1];
            String ele = textArray[Integer.parseInt(row) - 1];
            if (StringUtils.isEmpty(ele)) {
                ele = key + ":" + value[0]+" ";
            }else {
                ele+=key + ":" + value[0]+" ";
            }
            textArray[Integer.parseInt(row) - 1] = ele;
        }
        return Arrays.asList(textArray);
    }

    /**
     * @param sourcePath
     * @param targetPath
     * @param textMap
     * @param option     水印参数
     * @return
     */
    @SneakyThrows
    public static Boolean waterMark(String sourcePath, String targetPath, LinkedHashMap<String, String[]> textMap, WatermarkOption option) {
        logger.info("源文件：{}, 目标文件：{}", sourcePath, targetPath);

        try {
            // 读取原图像
            BufferedImage image = ImageIO.read(Paths.get(sourcePath).toFile());
            // 创建目标图像，大小与原图像相同
            BufferedImage targetImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
            // 获取目标图像的画笔
            Graphics2D g2d = (Graphics2D) targetImage.getGraphics();
            // 将原图像绘制到目标图像上
            g2d.drawImage(image, 0, 0, null);
            // 设置透明度、颜色、字体和文字抗锯齿效果
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, option.getAlpha()));
            g2d.setColor(option.getColor());
            g2d.setFont(option.getFont());
            g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            // 获取每行字符串的高度、最大宽度和行数
            int stringHeight = getStringHeight(g2d);
            // 绘制每行文字的灰色矩形背景和水印字符串
            g2d.setColor(option.getColor());
            g2d.setFont(option.getFont());
            g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            List<String> textList = buildTextList(textMap);
            int y = image.getHeight() - 250;
            for (int i = 0, size = textList.size(); i < size; i++) {
                y += 55;
                int statStationX = (image.getWidth() - g2d.getFontMetrics().stringWidth(textList.get(i))) / 2;
                g2d.drawString(textList.get(i), statStationX, y);
            }
            // 释放资源
            g2d.dispose();
            String extension = FilenameUtils.getExtension(targetPath);
            if (!Paths.get(targetPath).getParent().toFile().exists()) {
                Paths.get(targetPath).getParent().toFile().mkdirs();
            }
            ImageIO.write(targetImage, extension, Paths.get(targetPath).toFile());
            return Boolean.TRUE;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException("添加文字水印操作异常");
        }
    }

    /**
     * 获取画笔对象的字体高度
     *
     * @param g2d 画笔对象
     * @return 字体高度
     */
    private static int getStringHeight(Graphics2D g2d) {
        FontMetrics fm = g2d.getFontMetrics();
        // 计算字体高度并返回
        return fm.getAscent() + fm.getLeading() + fm.getDescent();
    }

    /**
     * 水印参数。
     */
    public static class WatermarkOption {
        private int x;
        private int y;
        private float alpha;
        private Color color;
        private Font font;

        public static WatermarkOption buildDefaultOptions() {
            WatermarkOption watermarkOption = new WatermarkOption();
            watermarkOption.x = 650;
            watermarkOption.y = 1750;//1750
            watermarkOption.alpha = 1.0f;
            watermarkOption.color = Color.YELLOW;
            watermarkOption.font = new Font("宋体", Font.BOLD, 45);
            return watermarkOption;
        }

        public static WatermarkOption custom() {
            return new WatermarkOption();
        }

        public int getX() {
            return x;
        }

        public WatermarkOption setX(int x) {
            this.x = x;
            return this;
        }

        public int getY() {
            return y;
        }

        public WatermarkOption setY(int y) {
            this.y = y;
            return this;
        }

        public float getAlpha() {
            return alpha;
        }

        public WatermarkOption setAlpha(float alpha) {
            this.alpha = alpha;
            return this;
        }

        public Color getColor() {
            return color;
        }

        public WatermarkOption setColor(Color color) {
            this.color = color;
            return this;
        }

        public Font getFont() {
            return font;
        }

        public WatermarkOption setFont(Font font) {
            this.font = font;
            return this;
        }
    }
}

